<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="commoditycode">
        <el-input
          v-model="queryParams.commoditycode"
          placeholder="请输入商品编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="productname">
        <el-input
          v-model="queryParams.productname"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="creationdate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.creationdate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="modifydate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.modifydate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:commodity:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:commodity:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:commodity:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:commodity:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commodityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键ID" align="center" prop="id"/>
      <el-table-column label="商品编码" align="center" prop="commoditycode"/>
      <el-table-column label="商品名称" align="center" prop="productname"/>
      <el-table-column label="商品单价" align="center" prop="productprice"/>
      <el-table-column label="商品图片" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.productimages"
            fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品描述" align="center" prop="productdesc"/>
      <el-table-column label="商品数量" align="center" prop="productcount"/>
      <el-table-column label="创建者" align="center" prop="createdby"/>
      <el-table-column label="创建时间" align="center" prop="creationdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creationdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="modifyby"/>
      <el-table-column label="更新时间" align="center" prop="modifydate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifydate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:commodity:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:commodity:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="commoditycode">
              <el-input v-model="form.commoditycode" placeholder="请输入商品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productname">
              <el-input v-model="form.productname" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品数量" prop="productcount">
              <el-input v-model="form.productcount" placeholder="请输入商品数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品单价" prop="productprice">
              <el-input-number v-model="form.productprice" controls-position="right" :min="0" placeholder="请输入商品单价"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建者" prop="createdby">
              <el-select v-model="form.createdby" placeholder="请选择创建者">
                <el-option
                  v-for="item in users"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新者" prop="modifyby">
              <el-select v-model="form.modifyby" placeholder="请选择更新者">
                <el-option
                  v-for="item in users"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片" prop="productimages">
              <div class="user-info-head">
                <img v-bind:src="productimages" title="上传图片" class="block" style="width: 40%; height: 40%"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col >
            <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
              <el-button size="small">
                选择<i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品描述" prop="productdesc">
              <el-input v-model="form.productdesc" type="textarea" placeholder="请输入商品描述"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listCommodity, getCommodity, delCommodity, addCommodity, updateCommodity, uploadCommodityImg} from "@/api/system/commodity";
  import {listUser} from "@/api/system/user";
  import {VueCropper} from "vue-cropper";

  export default {
    components: {VueCropper},
    name: "commodity",
    data() {
      return {
        autoUpload: true,//自动上传
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品表格数据
        commodityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          commoditycode: null,
          productname: null,
          creationdate: null,
          modifydate: null,
        },
        productimages: null,
        users: [],
        // 表单参数
        form: {
          productimages: null
        },
        // 表单校验
        rules: {
          commoditycode: [
            { required: true, message: "商品编码不能为空", trigger: "blur" }
          ],
          productname: [
            { required: true, message: "商品名称不能为空", trigger: "blur" }
          ],
          productcount: [
            { required: true, message: "商品数量不能为空", trigger: "blur" }
          ],
          productprice: [
            { required: true, message: "商品价格不能为空", trigger: "blur" }
          ],
          createdby: [
            { required: true, message: "创建人不能为空", trigger: "blur" }
          ],
          modifyby: [
            { required: true, message: "更新人不能为空", trigger: "blur" }
          ],
          productimages: [
            { required: true, message: "图片不可不上传", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getUsers();
    },
    methods: {
      // 覆盖默认的上传行为
      requestUpload() {
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") == -1) {
          this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        } else {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            this.productimages = reader.result;
            this.form.productimages = reader.result;
          };
          let formData = new FormData();
          formData.append("imgFile", file);
          uploadCommodityImg(formData).then(rsp => {
            this.productimages = rsp.data;
            this.form.productimages = rsp.data;
            this.$modal.msgSuccess("上传成功");
          })
        }
      },
      getUsers() {
        listUser().then(response => {
          this.users = response.rows;
        })
      },
      /** 查询商品列表 */
      getList() {
        this.loading = true;
        listCommodity(this.queryParams).then(response => {
          this.commodityList = response.rows;
          this.commodityList.forEach(commodity => {
            if (commodity.createdSysUser != null) commodity.createdby = commodity.createdSysUser.userName
            if (commodity.modifySysUser != null) commodity.modifyby = commodity.modifySysUser.userName
          })
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.productimages = null
        this.form = {
          id: null,
          commoditycode: null,
          productname: null,
          productdesc: null,
          productcount: null,
          createdby: null,
          creationdate: null,
          modifyby: null,
          modifydate: null,
          providerid: null,
          productimages: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.productimages = ""
        console.log(this.productimages)
        this.title = "添加商品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getCommodity(id).then(response => {
          this.form = response.data;
          this.productimages = response.data.productimages
          this.open = true;
          this.title = "修改商品";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            console.log(this.form)
            if (this.form.id != null) {
              updateCommodity(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCommodity(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function () {
          return delCommodity(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/commodity/export', {
          ...this.queryParams
        }, `commodity_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
